package lumis.content.source.field;

import java.util.Collection;

import lumis.content.ContentManagerFactory;
import lumis.content.core.Content;
import lumis.content.core.ContentLocale;
import lumis.content.table.ContentMetaDataController;
import lumis.content.table.ContentQueryBuilder;
import lumis.content.table.ContentTableSource;
import lumis.doui.DouiContext;
import lumis.doui.render.RenderDataValue;
import lumis.doui.source.ISourceData;
import lumis.doui.source.field.type.SourceFieldTypes;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.localization.LocaleConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.serviceinterface.IServiceInterfaceUrl;
import lumis.portal.serviceinterface.ServiceInterfaceConfig;
import lumis.portal.transaction.ITransaction;
import lumis.portal.transaction.PortalTransactionFactory;
import lumis.util.XmlUtil;

/**
 * Provides locale metadata information for the current row.
 *
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class LocaleMetaDataSourceField extends MetaDataSourceField
{
	public LocaleMetaDataSourceField() throws PortalException
	{
		super(ContentQueryBuilder.CONTENT_LOCALE_RELATION_ID, "locale", SourceFieldTypes.STRING);
	}

	@Override
	public void convertRowToFieldData(ISourceData databaseRow, ISourceData sourceRow) throws PortalException
	{
		ITransaction transaction = PortalTransactionFactory.getCurrentTransaction();
		
		if(source.getDouiContext() == null)
			return;
		
		String editInterfaceId = source.getEditInterfaceId();
		if(editInterfaceId == null)
			return;
		ServiceInterfaceConfig editServiceInterfaceConfig = ManagerFactory.getServiceInterfaceManager().getServiceInterfaceConfig(editInterfaceId, transaction);
		String windowProperties = editServiceInterfaceConfig.getPopupWindowProperties();
		String onEditClickScript = "window.open('openurl','_blank', '"+windowProperties+"');return false;";

		String addInterfaceId = source.getAddInterfaceId();
		if(addInterfaceId == null)
			return;
		ServiceInterfaceConfig addServiceInterfaceConfig = ManagerFactory.getServiceInterfaceManager().getServiceInterfaceConfig(addInterfaceId, transaction);
		windowProperties = addServiceInterfaceConfig.getPopupWindowProperties();
		String onAddClickScript = "window.open('openurl','_blank', '"+windowProperties+"');return false;";
		
		StringBuffer description = new StringBuffer();
		
		String contentId = databaseRow.get("contentId", String.class);
		String languageId = databaseRow.get("language", String.class);
		
		if(contentId == null || contentId.length() < 1 || languageId == null || languageId.length() < 1)
			return;
		
		StringBuffer localesValueString = new StringBuffer();
		String primaryKeyId = ((ContentTableSource)source).getPrimaryKeyField().getId();
		localesValueString.append("<locales>");
		
		Collection<LocaleConfig> globalLocales = ManagerFactory.getLocalizationManager().getLocales(transaction);
		Content curContent = ContentManagerFactory.getContentManager().getContent(contentId);
		Collection<ContentLocale> contentLocales = curContent.getContentLocales();
		
		for(LocaleConfig globalLocale : globalLocales)
		{
			localesValueString.append("<locale");
			localesValueString.append(" localeId=\""+XmlUtil.encodeXml(globalLocale.getLocale())+"\"");
			localesValueString.append(" name=\""+XmlUtil.encodeXml(globalLocale.getName())+"\"");
			boolean contentExists = false;
			for(ContentLocale contentLocale : contentLocales)
			{
				if(globalLocale.getLocale().toString().equals(contentLocale.getLocale().toString()))
				{
					if(description.length() > 0)
						description.append(", ");
					description.append(contentLocale.getLocale().getDisplayLanguage(SessionConfig.getCurrentSessionConfig().getLocale()));
					
					DouiContext douiContext = source.getDouiContext();
					IServiceInterfaceUrl serviceInterfaceUrl = douiContext.getResponse().createRenderURL();
					serviceInterfaceUrl.setRunTimeServiceInterfaceId(editInterfaceId);
					serviceInterfaceUrl.setRunTimeServiceInstanceId(douiContext.getRenderRequest().getServiceInstanceConfig().getId());
					serviceInterfaceUrl.setParameter(primaryKeyId, contentLocale.getActiveVersion().getItemId());
					
					localesValueString.append(" contentExists=\"yes\"");
					
					String onClickString = onEditClickScript.replaceFirst("openurl", serviceInterfaceUrl.toString());
					localesValueString.append(" onclick=\""+XmlUtil.encodeXml(onClickString)+"\"");

					contentExists = true;
					break;
				}
			}

			if(!contentExists)
			{
				DouiContext douiContext = source.getDouiContext();
				IServiceInterfaceUrl serviceInterfaceUrl = douiContext.getResponse().createRenderURL();
				serviceInterfaceUrl.setRunTimeServiceInterfaceId(addInterfaceId);
				serviceInterfaceUrl.setRunTimeServiceInstanceId(douiContext.getRenderRequest().getServiceInstanceConfig().getId());
				serviceInterfaceUrl.setParameter("language."+ContentMetaDataController.LANGUAGE_ID_PARAMETER_SUFIX, globalLocale.getLocale());
				serviceInterfaceUrl.setParameter("language."+ContentMetaDataController.CONTENTID_PARAMETER_SUFIX, contentId);
				
				String onClickString = onAddClickScript.replaceFirst("openurl", serviceInterfaceUrl.toString());
				localesValueString.append(" onclick=\""+XmlUtil.encodeXml(onClickString)+"\"");
			}
				
			localesValueString.append("/>");
		}
		
		localesValueString.append("</locales>");
		
		RenderDataValue localesValue = new RenderDataValue("<currentLocale>"+languageId+"</currentLocale>"+localesValueString.toString());
		
		sourceRow.put("language", localesValue);
	}
}
